# coding = utf-8
import logging
import os
from io import BytesIO

from PIL import Image
from django.db.models import Q, F
from django.http import HttpResponse
from lawoffice import settings

from rest_framework import mixins, exceptions, status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet, GenericViewSet
from wxchat.api.permissions import WeixinPermission

from service.models import PersonInfo, CompanyInfo, PrivateContract, CompanyContract, ContractAmount, \
    PrivateContractAmount, CompanyPerson, CardAgencyPerson, ConsultCard, Contact
from wxchat.models import WxUserInfo

from .serializers import PersonInfoSerializer, CompanyInfoSerializer, PrivateContractSerializer, \
    CompanyContractSerializer, ContractAmountSerializer, PrivateAmountSerializer, CompanyPersonSerializer, \
    CardAgencyPersonSerializer, ConsultCardSerializer, ContactSerializer
from wxchat.utils import get_openid_from_header, create_qrcode, mergeRightImage

logger = logging.getLogger("django")


def get_user(openid):
    if openid is None:
        return None
    user = WxUserInfo.objects.filter(openid=openid).first()
    return user


class PersonInfoViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    # permission_classes = (WeixinPermission, )
    pagination_class = None
    queryset = PersonInfo.objects.all()
    serializer_class = PersonInfoSerializer
    lookup_field = 'openid'
    lookup_url_kwarg = 'openid'


class CompanyInfoViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = CompanyInfo.objects.all()
    serializer_class = CompanyInfoSerializer
    lookup_field = 'openid'
    lookup_url_kwarg = 'openid'


class ContractAmountViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = ContractAmount.objects.all()
    serializer_class = ContractAmountSerializer


class PrivateAmountViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = PrivateContractAmount.objects.all()
    serializer_class = PrivateAmountSerializer


class PrivateContractViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = PrivateContract.objects.all()
    serializer_class = PrivateContractSerializer

    def get_queryset(self):
        openid = get_openid_from_header(self.request)
        logger.info("PrivateContractViewSet:get_queryset:{}".format(openid))
        queryset = super().get_queryset()
        if openid:
            user = get_user(openid)
            if user is None:
                return None

            if self.lookup_field in self.kwargs:
                return queryset

            if user and user.is_super:
                return queryset
            else:
                return queryset.filter(Q(openid=openid) | Q(office_openid=openid) | Q(agency_openid=openid))
        else:
            return None

    def get_object(self):
        obj = super().get_object()
        # print('get_object', obj.name)
        # if not obj.is_success:
        #     openid = get_openid_from_header(self.request)
        #     print(openid, '::get_object')
        #     if openid:
        #         user = get_user(openid)
        #         print(user, user.member_role_id)
        #         if user and user.member_role_id:
        #             obj.office_openid = openid
        #             obj.office_man = user.name
        #             obj.office_man_tel = user.telephone
        #             obj.save()
        return obj


class CompanyContractViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = CompanyContract.objects.all()
    serializer_class = CompanyContractSerializer

    def get_queryset(self):
        openid = get_openid_from_header(self.request)
        print(openid, 'CompanyContractViewSet')
        queryset = super().get_queryset()
        if openid:
            user = get_user(openid)
            if user is None:
                return None
            if self.lookup_field in self.kwargs:
                return queryset

            if user and user.is_super == 1:
                return queryset
            else:
                return queryset.filter(Q(openid=openid) | Q(office_openid=openid) | Q(agency_openid=openid))
        else:
            return None

    def get_object(self):
        obj = super().get_object()
        # if not obj.is_success:
        #     openid = get_openid_from_header(self.request)
        #     logger.info('CompanyContractViewSet :get_object:{}'.format(openid))
        #     if openid:
        #         user = get_user(openid)
        #         if user and user.member_role_id in [1, 2, 3]:      # member_role[ 2 为法律顾问代理]
        #             obj.office_openid = openid
        #             obj.office_man = user.name
        #             obj.office_man_tel = user.telephone
        #             if user.member_role_id == 2:
        #                 obj.category = 1
        #             obj.save()
        return obj


class CompanyAgencyViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = CompanyInfo.objects.all()
    serializer_class = CompanyInfoSerializer

    def get_queryset(self):
        openid = get_openid_from_header(self.request)
        logger.info('CompanyAgencyViewSet:{}'.format(openid))
        queryset = super().get_queryset()
        if openid:
            user = get_user(openid)
            if user is None:
                return None
            if self.lookup_field in self.kwargs:
                return queryset

            if user and user.is_super == 1:
                return queryset.filter(Q(office_openid=openid) | Q(is_agency=1))
            else:
                return queryset.filter(office_openid=openid)
        else:
            return CompanyInfo.objects.none()

    def get_object(self):
        obj = super().get_object()
        logger.info(obj)
        if not obj.is_agency:
            openid = get_openid_from_header(self.request)
            logger.info('CompanyAgencyViewSet :get_object:{}'.format(openid))
            if openid:
                user = get_user(openid)
                if user.openid == obj.office_openid:
                    return obj

                obj.openid = openid
                obj.is_agency = 1
                obj.save()

                user.member_role_id = 2     # 第三方代理
                user.save()

        return obj


class CompanyPersonAgencyViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = CompanyPerson.objects.all()
    serializer_class = CompanyPersonSerializer


class CardAgencyPersonViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = CardAgencyPerson.objects.all()
    serializer_class = CardAgencyPersonSerializer

    def get_queryset(self):
        openid = get_openid_from_header(self.request)
        logger.info('CardAgencyPersonViewSet:{}'.format(openid))
        queryset = super().get_queryset()
        if openid:
            user = get_user(openid)
            if user is None:
                return None
            if self.lookup_field in self.kwargs:
                return queryset

            if user and user.is_super == 1:
                return queryset.filter(Q(is_agency=1))
            else:
                return queryset.filter(Q(office_openid=openid))
        else:
            return CardAgencyPerson.objects.none()


class ConsultCardViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = ConsultCard.objects.all()
    serializer_class = ConsultCardSerializer

    def create(self, request, *args, **kwargs):
        openid = request.data["openid"]

        card_counts = ConsultCard.objects.filter(openid=openid, is_used=0).count()
        if card_counts >= 1:
            msg = {
                'status_code': status.HTTP_401_UNAUTHORIZED,
                'message': '您目前有未使用的咨询卡，请使用完再申请咨询卡!'
            }
            return Response(msg, status=status.HTTP_201_CREATED)

        agency_openid = request.data["agency_openid"]
        user = WxUserInfo.objects.filter(openid=openid).first()

        data = {
            'openid': openid,
            'agency_openid': agency_openid,
            'name': user.name if user.name else user.nickname
        }
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def get_queryset(self):
        openid = get_openid_from_header(self.request)
        logger.info('ConsultCardViewSet:{}'.format(openid))
        queryset = super().get_queryset()
        if openid:
            user = get_user(openid)
            if user is None:
                return None
            if self.lookup_field in self.kwargs:
                return queryset

            if user and user.is_super == 1:
                return queryset.filter(is_used=0)
            else:
                return queryset.filter(Q(openid=openid) | Q(agency_openid=openid), is_used=0)
        else:
            return ConsultCard.objects.none()

    def get_object(self):
        obj = super().get_object()

        return obj


class CompanyInfoAPIView(ListAPIView):
    """代理公司查询"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    serializer_class = CompanyInfoSerializer
    queryset = CompanyInfo.objects.all()

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)
        if name:
            return queryset.filter(name=name, is_agency=1)
        else:
            return CompanyInfo.objects.none()


class ContactListAPIView(ListAPIView):
    """联系人"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    serializer_class = ContactSerializer
    queryset = Contact.objects.all()

    def get_queryset(self):
        queryset = super().get_queryset()
        unit_name = self.request.query_params.get("unit_name", None)
        dept_name = self.request.query_params.get("dept_name", None)
        name = self.request.query_params.get("name", None)
        if unit_name:
            queryset = queryset.filter(unit_name__contains=unit_name)

        if dept_name:
            queryset = queryset.filter(dept_name__contains=dept_name)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset





